import Api from '@/api';
import { Message } from 'element-ui';

export default {
  namespaced: true,
  state: {
    //用户信息
    info: {
      email: '',
      avatar: '',
    },
  },
  mutations: {
    setState(state, payload) {
      const keys = Object.keys(payload) || [];
      keys.forEach(key => {
        state[key] = payload[key];
      });
    },
    setInfo(state, payload = {}) {
      state.info = { ...state.info, ...payload };
    },
  },
  actions: {
    async checkUserInfo({ state, dispatch }) {
      const { info } = state;
      if (!info || !info.id) {
        return await dispatch('getUserInfo');
      }
      return !!info;
    },
    async getUserInfo({ state, commit, dispatch }, payload = {}) {
      commit('setState', { globalLoading: true }, { root: true });
      const res = await Api.getUserInfo().catch(e => {
        // Message.error('获取用户信息失败');
        console.error('获取用户信息失败');
        commit(
          'setState',
          {
            globalLoading: false,
          },
          { root: true },
        );
      });
      if (res) {
        const { data } = res;
        commit('setInfo', data);
        return data;
      }
      return null;
    },
  },
};
